﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace ZCustomControl.Helpers
{
    public class LVTreeHelper
    {
        public static T GetAncestor<T>(DependencyObject source) where T : DependencyObject
        {
            if (source == null)
                return null;
            do
            {
                source = VisualTreeHelper.GetParent(source);
            } while (source != null && !(source is T));

            return source as T;
        }

        /// <summary>
        /// 返回鼠标点击中的元素的父级元素
        /// </summary>
        /// <typeparam name="T">要获取的祖先的类型。</typeparam>
        /// <param name="source">获取的祖先，如果不存在则为 <c>null</c>。</param>
        /// <returns>获取的祖先对象。</returns>
        public static T GetAncestor<T>(MouseEventArgs e, IInputElement relativeTo) where T : DependencyObject
        {
            Point pos = e.GetPosition(relativeTo);
            HitTestResult hitResult = VisualTreeHelper.HitTest(relativeTo as Visual, pos);
            if (hitResult != null)
            {
                return GetAncestor<T>(hitResult.VisualHit);
            }

            return null;
        }

        public static T FindVisualParent<T>(DependencyObject obj) where T : class
        {
            while (obj != null)
            {
                if (obj is T)
                    return obj as T;

                obj = VisualTreeHelper.GetParent(obj);
            }

            return null;
        }

        /// <summary>
        /// 获取控件的嵌套深度
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="item"></param>
        /// <returns></returns>
        public static int GetDepth<T>(T item) where T : DependencyObject
        {
            int depth = 0;
            while ((item = GetAncestor<T>(item)) != null)
            {
                depth++;
            }
            return depth;
        }
    }
}
